﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eShop.Model;
using eShop.Business;

public partial class admin_controls_content_form : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindFormDataToUI();
            BindModelToUI();
        }
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                SaveContent();
                uccResponseMessage.SetSuccessMessage("Data saved successfully");
                uccResponseMessage.Visible = true;
            }
        }
        catch (Exception exception)
        {
            uccResponseMessage.SetFailMessage("Failed to save data." + "<br />" + exception.Message);
            uccResponseMessage.Visible = true;
        }
        finally
        {
            BindModelToUI();
        }
    }

    private void BindFormDataToUI()
    {
    }

    private void BindModelToUI()
    {
        if (Id > 0)
        {
            CMS content = LoadContent();
            BindContentToUI(content);
        }
        else
        {
            ClearUI();
        }
    }

    private void ClearUI()
    {
        tbTitle.Text = "";
        tbContent.Text = "";
    }

    private void BindContentToUI(CMS content)
    {
        tbTitle.Text = content.CMSTitle;
        tbContent.Text = content.CMSContent;
    }

    private CMS LoadContent()
    {
        if (Id > 0)
        {
            return CMSManager.GetCMS(Id);
        }
        else
        {
            return new CMS();
        }
    }

    private void SaveContent()
    {
        CMS content = LoadContent();
        content.CMSTitle = tbTitle.Text.Trim();
        content.CMSContent = tbContent.Text.Trim();

        if (content.CMSId > 0)
        {
            CMSManager.Update(content);
        }
        else
        {
            CMSManager.Create(content);
        }
    }

    private Int32? _id;
    private Int32 Id
    {
        get
        {
            if (!_id.HasValue)
            {
                try
                {
                    if (HttpContext.Current.Request.QueryString != null && !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["cmsid"]))
                    {
                        _id = Convert.ToInt32(HttpContext.Current.Request.QueryString["cmsid"]);
                    }
                    else
                    {
                        _id = -1;
                    }
                }
                catch
                {
                    _id = -1;
                }
            }
            return _id.Value;
        }
    }
}